package com.shd.edanpei.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.shd.edanpei.R;
import com.shd.edanpei.base.MyApplication;
import com.shd.edanpei.util.FileUtils;
import com.shd.edanpei.util.IntentUtils;
import com.shd.edanpei.util.ScreenUtils;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;


public class ChoosePicActivity extends Activity implements View.OnClickListener {

    private static final String TAG = ChoosePicActivity.class.getSimpleName();
    //        public static final String SDCARD_ROOT = Environment.getExternalStorageDirectory().getPath();
    public static final String SDCARD_ROOT = MyApplication.getApplication().getExternalCacheDir().getPath();
    //    public static final String MY_SDCARD_ROOT = SDCARD_ROOT + "/zhuoxun/";              //应用数据保存路径
    public static final String SCARD_PIC_PATH = SDCARD_ROOT + "/picture/";               //用户图片保存路径
    public static final String SCARD_ERRORLOG_PATH = SDCARD_ROOT + "log.txt";

    public static final String INTENT_BACK_DATA = "bitmap_back";
    public static final String INTENT_RESULT_CODE = "result_code";

    public static final int INTENT_REQUEST_CODE = 99;

    private static final int REQUEST_PICK_IMAGE = 91;    //相册选取
    private static final int REQUEST_CAPTURE = 92;       //拍照
    private static final int REQUEST_PICTURE_CUT = 93;   //剪裁图片


    private RxPermissions mRxPermissions;

    private Uri imageUri;//原图保存地址

    private int mResultCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setFinishOnTouchOutside(true);
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.width = ScreenUtils.getScreenWidth(this);
        getWindow().setAttributes(attributes);
        getWindow().setGravity(Gravity.BOTTOM);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choosepic_activity);
        ButterKnife.bind(this);
        initView();
        if (savedInstanceState == null) {
          //  Log.e(Tag, "-------onCreate--------"+savedInstanceState);
        }else{
          savedInstanceState.getString("cropPhotoPath");
        }

    }

    private void initView() {
        mResultCode = getIntent().getIntExtra(INTENT_RESULT_CODE, INTENT_REQUEST_CODE);
        mRxPermissions = new RxPermissions(this);
    }

    @Override
    @OnClick({R.id.tv_editdata_camera, R.id.tv_editdata_gallery, R.id.tv_editdata_cancel})
    public void onClick(final View view) {
        if (view.getId() == R.id.tv_editdata_cancel) {
            finish();
            return;
        }
        mRxPermissions.request(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@android.support.annotation.NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            switch (view.getId()) {
                                case R.id.tv_editdata_camera:
                                    //检查权限(6.0以上做权限判断)
                                    openCamera();
                                    break;
                                case R.id.tv_editdata_gallery:
                                    selectFromAlbum();
                                    break;
                                default:
                                    break;
                            }

                        } else {
                            View view = LayoutInflater.from(ChoosePicActivity.this).inflate(R.layout.dialog_power, null);
                            TextView tvContent = view.findViewById(R.id.tv_dialog_a_content);
                            TextView tvCancel = view.findViewById(R.id.tv_dialog_c_cancel);
                            TextView tvSure = view.findViewById(R.id.tv_dialog_c_sure);
                            tvContent.setText(getResources().getString(R.string.camera_permission_disabled));
                            final Dialog dialog = new Dialog(ChoosePicActivity.this, R.style.dialog);
                            dialog.setContentView(view);
                            dialog.setCanceledOnTouchOutside(true);
                            tvCancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.dismiss();
                                }
                            });
                            tvSure.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(IntentUtils.getAppDetailSettingIntent());
                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
//                            AlertDialog.Builder builder = new AlertDialog.Builder(ChoosePicActivity.this);
//                            builder.setTitle("开启权限")
//                                    .setMessage("访问通讯录权限被禁止，请到权限设置中打开！")
//                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            dialog.dismiss();
//                                        }
//                                    })
//                                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            startActivity(IntentUtils.getAppDetailSettingIntent());
//                                            dialog.dismiss();
//                                        }
//                                    })
//                                    .show();
                        }
                    }
                });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.trans_bottom_in, R.anim.trans_bottom_out);
    }

    /**
     * 打开系统相机
     */
    private String cameraPhotoPath;

    private void openCamera() {
        cameraPhotoPath = SCARD_PIC_PATH + System.currentTimeMillis() + ".png";
        File file = FileUtils.getFileByPath(cameraPhotoPath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(ChoosePicActivity.this, getPackageName() + ".provider", file);
            //通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 从相册选择
     */
    private void selectFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQUEST_PICK_IMAGE);
    }

    /**
     * 裁剪
     */
    private String cropPhotoPath;

    private void cropPhoto() {
        cropPhotoPath = SCARD_PIC_PATH + System.currentTimeMillis() + ".png";
        File cropFile = FileUtils.getFileByPath(cropPhotoPath);
        Uri outputUri = Uri.fromFile(cropFile);//缩略图保存地址
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUEST_PICTURE_CUT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PICK_IMAGE://从相册选择
                imageUri = data.getData();
                cropPhoto();
                break;
            case REQUEST_CAPTURE://拍照
                if (resultCode == RESULT_OK) {
                    cropPhoto();
                }
                break;
            case REQUEST_PICTURE_CUT://裁剪完成
                setBackData(cropPhotoPath);
                break;
            default:
                break;
        }
    }

    private void setBackData(String picPath) {
        composePic(picPath);
        Intent intent = new Intent();
        intent.putExtra(INTENT_BACK_DATA, picPath);
        setResult(mResultCode, intent);
        finish();
    }

    /**
     * 压缩本地图片  减少上传图片超时概率
     */
    private void composePic(String photoName) {
        printFileSize(photoName);

        BitmapFactory.Options op = new BitmapFactory.Options();
        op.inSampleSize = 2; // 这个数字越大,图片就越小.图片就越不清晰

        Bitmap pic = null;
        pic = BitmapFactory.decodeFile(photoName, op);  //先从本地读照片，然后利用op参数对图片进行处理

        //将处理后的图片重新写回本地
        FileOutputStream b = null;
        try {
            b = new FileOutputStream(photoName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (pic != null) {
            pic.compress(Bitmap.CompressFormat.JPEG, 50, b);
        }

        printFileSize(photoName);
    }

    private void printFileSize(String fileName) {
        try {
            File file = new File(fileName);
            if (file == null) {
                KLog.d(TAG, "fileSize:" + 0);
            }
            long size = 0;
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            }
            KLog.d(TAG, "fileSize:" + size);
        } catch (Exception e) {
        }
    }

    /**
     * start
     *
     * @param activity
     * @param code     返回码
     */
    public static void start(Activity activity, int code) {
        Intent intent = new Intent(activity, ChoosePicActivity.class);
        intent.putExtra(INTENT_RESULT_CODE, code);
        activity.startActivityForResult(intent, INTENT_REQUEST_CODE);
        activity.overridePendingTransition(R.anim.trans_bottom_in, R.anim.trans_bottom_out);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("cropPhotoPath",cropPhotoPath);
    }

//    @Override
//    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
//    }
}
